package com.roc.web.action.agent;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.TermBean;
import com.roc.bean.orgMainBean;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.ProfitModule;
import com.roc.pojo.ProfitPercent;
import com.roc.pojo.ProfitRule;
import com.roc.pojo.TblArea;
import com.roc.service.IAgentService;
import com.roc.service.IMerchantServices;
import com.roc.service.IModelService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.DateUtil;
import com.roc.util.Utils;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.InvoiceRateType;
import com.roc.util.constant.MerberFlag;
import com.roc.util.constant.ProfitModuleStatus;
import com.roc.util.constant.Role;
import com.roc.util.constant.TblBlackInfType;
@Component
@Namespace("/agent")
@SuppressWarnings("all")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class AgentAction extends PaginationBaseAction{
	static Logger logger = Logger.getLogger(AgentAction.class);
	@Autowired
	IorgService orgService;
	@Autowired
	IAgentService  agentService;
	@Autowired
	IModelService modelService;
	@Autowired
	private IPowerInfoService operatorService;
	@Autowired
	IPowerInfoService powerInfoService;
	
	private Operators agent;
	
	private List<ProfitPercent> profitPerList;
	//代理申请
	@Action(value = "addAgent", results = {
			@Result(name = "success",type="chain", location = "agentJsp"),
			@Result(name = "error", location = "/error.jsp") }
	)
	public String  applyAgent(){
		Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		String pwd = "";
		String showRoleName = String.valueOf(Role.valueOfCode( agent.getRoleType() ).getName());
		try {
			// 如果当前登录账号非系统管理员/机构管理员/代理商，没有权限登陆
			if(!logingOperators.getRoleType().equals(Role.AGENT.getCode()) && !logingOperators.getRoleType().equals(Role.SYSTEM.getCode())
					&& !logingOperators.getRoleType().equals(Role.OPERATORS_COMM.getCode()) && !logingOperators.getRoleType().equals(Role.OPERATORS_LEAD.getCode())
					 && !logingOperators.getRoleType().equals(Role.O_MANAGER.getCode()) ){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			
			if( !Utils.checkAccountName( agent.getRealName() ) ) {
				addActionError("名称格式不正确，只能输入中英文，数字，括号和空格!");
				return ERROR;
			}
			// 校验手机号
			if( agentService.selectBlackInfoByType(TblBlackInfType.BT_1.getCode(), agent.getMobile()) > 0 ) {
				addActionError("手机号为黑名单用户，不可录入，开通失败!");
				return ERROR;
			}
			// 校验身份证 ,cardType -01
			if( agentService.selectBlackInfoByType(TblBlackInfType.BT_2.getCode(), agent.getCardNo()) > 0 ) {
				addActionError("证件号码为黑名单用户，不可录入，开通失败!");
				return ERROR;
			}

			Map<String, String> map=powerInfoService.queryRealIdByOpId(logingOperators.getSuperiorId(), logingOperators.getRoleType(), logingOperators.getId(), logingOperators.getOrgCode());
            String superRole= map.get("superRole");
			// 如果系统管理员/系统管理员下的运营 添加机构管理员【一级代理商】
			if( logingOperators.getRoleType().equals(Role.SYSTEM.getCode())
					 || ( superRole.equals(Role.SYSTEM.getCode()) 
							 && ( logingOperators.getRoleType().equals(Role.OPERATORS_COMM.getCode()) || logingOperators.getRoleType().equals(Role.OPERATORS_LEAD.getCode()) ) )  ){
				//判断当前机构管理员是否已存在
				String oneAgentOrgCode = agent.getOneagentid();
				Operators oneOrgOper = powerInfoService.queryOperByOneOrgCode(oneAgentOrgCode);
				if ( null != oneOrgOper ) {
					addActionError("此机构 机构管理员已存在，请重新选择机构!");
					return ERROR;
				}

				// 判断序号编码是否已存在
				// 通过机构管理编号查询所属区域
				orgMainBean orgMainObj = orgService.queryOrgMainByOrgMain( oneAgentOrgCode );
				String companyid = orgMainObj.getAreaId();
				agent.setCompanyid(companyid);

				String agentType = ""; 
				String agentNumber = agent.getOrganizationCode();
				agentType = powerInfoService.queryAgentNumberByAreaId(companyid);
				
				// 如果分公司序号为空或空字符，则序号默认为 0
				agentType = ( null == agentType || "".equals(agentType) ) ? Constant.OTHER_AGENTNUMBER : (agentType + "-");
				// 判断录入的序号编码是否已存在
				boolean isExist = powerInfoService.queryOperatorInfoByNumberCode(agentType  , agentNumber);
				if ( null == agent.getOrganizationCode() || "".equals(agent.getOrganizationCode().trim()) 
						|| ( true == isExist) ){
					addActionError("序号编码不能为空或者序号编码已存在，请重新输入!");
					return ERROR;
				}
				// 设置 序号编码  分公司编码+数字   例如：0_01,1_00001
				agent.setOrganizationCode(agentType + agentNumber);
			} 

			// 如果当前登录账号是机构管理员，并且账号名称中包含 云商宝 ，添加序号编码及税点【发票扣率】
			if( logingOperators.getRoleType().equals(Role.O_MANAGER.getCode())
					 && ( logingOperators.getRealName().contains(Constant.YSB_NAME) ) ){

				// 如果商户类别为直联，添加 序号编码及税点【发票扣率】
				 if ( agent.getGroupCd().equals("0") ) {
						// 判断序号编码是否已存在
						String companyid = logingOperators.getCompanyid();
						String agentType = ""; 
						String agentNumber = agent.getOrganizationCode();
						agentType = powerInfoService.queryAgentNumberByAreaId(companyid);
						
						// 如果分公司序号为空或空字符，则序号默认为 0
						agentType = ( null == agentType || "".equals(agentType) ) ? Constant.OTHER_AGENTNUMBER : (agentType + "-");
						// 判断录入的序号编码是否已存在
						boolean isExist = powerInfoService.queryOperatorInfoByNumberCode(agentType  , agentNumber);
						if ( null == agent.getOrganizationCode() || "".equals(agent.getOrganizationCode().trim()) 
								|| ( true == isExist) ){
							addActionError("序号编码不能为空或者序号编码已存在，请重新输入!");
							return ERROR;
						}
						// 设置 序号编码  分公司编码+数字   例如：0_01,1_00001
						agent.setOrganizationCode(agentType + agentNumber);
				 } else if( agent.getGroupCd().equals("2") ) { // 如果注册的是直营代理商， 序号编码设置为空
						agent.setOrganizationCode("");
				 } else { // 序号编码及税点【发票扣率】设置为空
						agent.setTaxRegistrationCertificate("");
						agent.setOrganizationCode("");
				 }
			}
			
			String isUseDefModule = agent.getIsUseDefModule();
			if(null != isUseDefModule && !isUseDefModule.equals("")){
				// 查询当前默认的模板信息
				ProfitModule bean = modelService.queryDefProfitModuleByAgentId( logingOperators.getId());

				// 如果查询模板id为空,返回异常
				if(null == bean){
					addActionError(showRoleName + "申请失败,默认分润模板不存在,请重新添加或设置默认模板!");
					return ERROR;
				}
			}

			// 如果添加的角色是机构管理员，supId取收单事业部id
			if ( agent.getRoleType().equals(Role.O_MANAGER.getCode()) ) {
		//		agent.setSuperiorId(new Long(agent.getCompanyid()));
				agent.setSuperiorId(new Long( Constant.SHOUDANSHIYEBU_ID ));
			} else {
				// 如果登陆角色是机构运营，supId取上级id
				if ( logingOperators.getRoleType().equals(Role.OPERATORS_COMM.getCode())  ){
					agent.setSuperiorId(logingOperators.getSuperiorId());
				}else {
					agent.setSuperiorId(logingOperators.getId());
				}
			}
		
			agent.setOperators(logingOperators.getAccountNo());
			if(agent.getRoleType().equals(Role.O_MANAGER.getCode())){
				agent.setFlag(Constance.OPERATORS_FLAG_OEM);//O单标志
			}else{
				agent.setFlag(logingOperators.getFlag());
			}
			if(Role.RISK_CONTROL_LEAD.getCode().equals(agent.getRoleType()) || Role.RISK_CONTROL_OPERATORS.getCode().equals(agent.getRoleType())){
			    agent.setAgentType("1");
                        }else{
                            agent.setAgentType("0");
                        }
			Date date=new Date();
			agent.setValidStartDate(DateUtil.initStartDate(date));
			agent.setValidEndDate(DateUtil.initEndDate());
			pwd = agentService.issueAgent(agent,logingOperators.getAccountNo(),logingOperators);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			addActionError("保存" + showRoleName + "信息出错,请联系管理员");
			return ERROR;
		}
		 getRequest().setAttribute("msg", showRoleName + "["+agent.getAccountNo()+"]录入成功,初始密码" + pwd);
		return SUCCESS;
	}
	//初始化加载页面
	@Action(value = "agentJsp", results = {
			@Result(name = "success", location = "/pages/agent/addAgent.jsp"),
			@Result(name = "error", location = "/error.jsp") }
	)
	public String  agentJsp(){
		List orgList=new ArrayList();
		// 分公司属性信息集
		List<TblArea> companyList = new ArrayList<TblArea>();
		List<orgMainBean> orgMainList = new ArrayList<orgMainBean>();
		
		try {
			
			Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			
			
			// 如果当前登录账号非系统管理员/机构管理员/代理商，没有权限登陆
			if(!logingOperators.getRoleType().equals(Role.AGENT.getCode()) && !logingOperators.getRoleType().equals(Role.SYSTEM.getCode())
					&& !logingOperators.getRoleType().equals(Role.OPERATORS_COMM.getCode()) && !logingOperators.getRoleType().equals(Role.OPERATORS_LEAD.getCode())
					 && !logingOperators.getRoleType().equals(Role.O_MANAGER.getCode())  ){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			orgList = orgService.queryAllOrgList();

			// 如果登录账号为机构管理员/代理商 ,查询当前机构下的分公司属性信息
			companyList = powerInfoService.queryAreaInfoByOrgCode( logingOperators.getOrgCode() );
			
			
			orgMainList = orgService.listOrgMainByOrgCode(logingOperators.getOrgCode());
			/*
			//orgList=orgService.listOrgs(logingOperators);
			// 如果登录账号为系统管理员，查询所有机构信息，且 分公司属性信息由 
			if ( logingOperators.getRoleType().equals(Role.SYSTEM.getCode()) ){

				orgList = orgService.queryAllOrgList();
			}else {
				// 如果登录账号为机构管理员/代理商 ,查询当前机构下的分公司属性信息
				companyList = powerInfoService.queryAreaInfoByOrgCode( logingOperators.getOrgCode() );
			}*/
			getRequest().setAttribute("companyList",companyList );
			getRequest().setAttribute("orgMainList",orgMainList );
			getRequest().setAttribute("op",logingOperators );
			

			Map<String, String> map=powerInfoService.queryRealIdByOpId(logingOperators.getSuperiorId(), logingOperators.getRoleType(), logingOperators.getId(), logingOperators.getOrgCode());
            String superRole= map.get("superRole");
            String opRealId =map.get("opRealId");
			
			String isShowAreaFlag = "0";
			// 如果当前登录账号/上级是系统管理员的运营人员，显示所属区域，序号编码【默认录入机构管理员[一级代理商]】
			if( logingOperators.getRoleType().equals(Role.SYSTEM.getCode())
					 || ( superRole.equals(Role.SYSTEM.getCode()) 
							 && ( logingOperators.getRoleType().equals(Role.OPERATORS_COMM.getCode()) || logingOperators.getRoleType().equals(Role.OPERATORS_LEAD.getCode()) ) ) ){
				isShowAreaFlag = "1";
			}

			getRequest().setAttribute("isShowAreaFlag", isShowAreaFlag );
			getRequest().setAttribute("superRole", superRole );

			String isRsbFlag = "0";
			// 如果当前登录账号是机构管理员，并且账号名称中包含 云商宝 ，显示所属区域，序号编码
			if( logingOperators.getRoleType().equals(Role.O_MANAGER.getCode())
					 && ( logingOperators.getRealName().contains(Constant.YSB_NAME) ) ){
				isRsbFlag = "1";
			}
			getRequest().setAttribute("isRsbFlag", isRsbFlag );
			
			Operators supOperator = powerInfoService.loadOperatorsById(new Long(opRealId));
			Map<String, String> mccMap = agentService.getMccArray4Agent(supOperator.getAccountNo(),supOperator.getRoleType());
/*
			// 如果是业务员录入代理商,取 业务员的上级代理商信息
			if(logingOperators.getRoleType().equals(Role.AGENT_BUSS.getCode())){
				Operators loginOps = powerInfoService.loadOperatorsById(logingOperators.getSuperiorId());
				mccMap = agentService.getMccArray4Agent(loginOps.getAccountNo(),loginOps.getRoleType());
			}*/
			
			getRequest().setAttribute("mccList",mccMap);//mcc
			getRequest().setAttribute("perList",getDefPer());//
			/*
			Map<String, String> map=dealAgentType(logingOperators.getFlag(), logingOperators.getAgentType(), ConfigProperties.getAgentTypeProperties());
			getRequest().setAttribute("agTypeList",map);
*/
			// 查询当前默认的模板信息
			ProfitModule bean = modelService.queryDefProfitModuleByAgentId(logingOperators.getId());
			int moduleSize = 0;
			if(null != bean){
				moduleSize = 1;
			}
			getRequest().setAttribute("moduleSize", moduleSize);
			
			getRequest().setAttribute("orgList", orgList);
			getRequest().setAttribute("areaList", ConfigProperties.getAreaCodeProperties());
			getRequest().setAttribute("merberFlagMap", MerberFlag.getAllEnumMap());

			getRequest().setAttribute("invoiceRateMap", InvoiceRateType.getAllEnumMap()); // 发票扣率Map
			
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(),e);
			addActionError("加载代理商基本信息出错！！");
		}
		return SUCCESS;
	}
	
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return null;
	}

	public Operators getAgent() {
		return agent;
	}

	public void setAgent(Operators agent) {
		this.agent = agent;
	}
	public List<ProfitPercent> getProfitPerList() {
		return profitPerList;
	}
	public void setProfitPerList(List<ProfitPercent> profitPerList) {
		this.profitPerList = profitPerList;
	}
	
	public HashMap<String,String> getDefPer(){
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("01", "01");
		map.put("02", "02");
		map.put("03", "03");
		map.put("04", "04");
		return map;
	}
	@Action(value="validateAccountNo")
	public void vilidateAccountNo()
	{
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		boolean value=true;
		try {
			agent=operatorService.validateAccount(agent.getAccountNo());
			if(agent!=null)
			{
				value=false;
			}
			response.getWriter().print(value);
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			addActionError("验证登陆账号错误!!!");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Action(value="vilidateAccountName")
	public void vilidateAccountName()
	{
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		boolean value = false;
		try {
			value = Utils.checkAccountName(agent.getRealName());
			
			response.getWriter().print(value);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError("验证登陆账号名称错误!!!");
		}
	}
}
